﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Streambolics.Gui
{
    public class DragAdapter
    {
        public struct IconInfo
        {
            public bool fIcon;
            public int xHotspot;
            public int yHotspot;
            public IntPtr hbmMask;
            public IntPtr hbmColor;
        }

        [DllImport ("user32.dll")]
        public static extern IntPtr CreateIconIndirect (ref IconInfo icon);

        [DllImport ("user32.dll")]
        [return: MarshalAs (UnmanagedType.Bool)]
        public static extern bool GetIconInfo (IntPtr hIcon, ref IconInfo pIconInfo);

        public static Cursor CreateCursor (Bitmap bmp,
            int xHotSpot, int yHotSpot)
        {

            IconInfo tmp = new IconInfo ();
            GetIconInfo (bmp.GetHicon (), ref tmp);
            tmp.xHotspot = xHotSpot;
            tmp.yHotspot = yHotSpot;
            tmp.fIcon = false;
            return new Cursor (CreateIconIndirect (ref tmp));
        }

        public static Cursor BuildCursor (Control aControl, MouseEventArgs e, bool aDisabled)
        {
            float scale = 1;

            if (aControl.Width > 128)
            {
                scale = 128.0f / aControl.Width;
            }

            if (aControl.Height > 64)
            {
                float ns = 64.0f / aControl.Height;
                if (ns < scale)
                {
                    scale = ns;
                }
            }

            // Choose an appropriate cursor

            Cursor c = aDisabled ? Cursors.No : Cursors.Arrow;

            Bitmap b = new Bitmap (32 + (int)(aControl.Width * scale + 0.5f), Math.Max (32, (int)(aControl.Height * scale + 0.5f)));
            Graphics g = Graphics.FromImage (b);

            //  Draw the cursor on the left-hand side of the icon
            //  TODO : adjust the drawing position according to the hotspot

            c.Draw (g, new Rectangle (0, 0, 32, 32));

            //  Draw the full control in its own rectangle
            //  TODO : check to see what happens if we use b directly.

            Bitmap cb = new Bitmap (aControl.Width, aControl.Height);
            aControl.DrawToBitmap(cb, new Rectangle (0, 0, aControl.Width, aControl.Height));

            //  Draw the control bitmap in the icon bitmap

            g.TranslateTransform (32, 0);
            g.ScaleTransform (scale, scale);
            g.DrawImage (cb, new Point (0, 0));

            if (aDisabled)
            {
                b.MakeTransparent (Color.White);
            }

            //  And make a cursor from the bitmap.

            return CreateCursor (b, c.HotSpot.X, c.HotSpot.Y);
        }

    }
}
